#include <QString>
#include <QIcon>
#include <QFileDialog>
#include <QEvent>
#include <QMouseEvent>
#include <QtDebug>

#include <iostream>
using namespace std;

#include "ui_mainwindow.h"
#include "mainwindow.h"
#include "listbutton.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    total_list = 0;
    cur_list = 0;
    cur_entry = 0;
    timer_of_timer = 0;

    ui->play->setIcon( QIcon(":/icon/play.png") );
    ui->stop->setIcon( QIcon(":/icon/stop.png") );
    ui->prev->setIcon( QIcon(":/icon/backward.png") );
    ui->next->setIcon( QIcon(":/icon/forward.png") );
    ui->addList->setIcon( QIcon(":/icon/add.png") );

    ui->verticalLayout->setSpacing(0);
    ui->verticalLayout->setContentsMargins(0, 0, 0, 0);

    ui->tableView->horizontalHeader()->hide();
    ui->tableView->verticalHeader()->hide();
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setAlternatingRowColors(true);

    QHBoxLayout *positionLayout = new QHBoxLayout(ui->frame_7);
    positionLayout->setSpacing(0);
    positionLayout->setContentsMargins(0, 0, 0, 0);
    position = new MySlider(tr("position"), ui->frame_7);
    position->setOrientation(Qt::Horizontal);
    position->setRange(0, 999);
    positionLayout->addWidget(position);
    connect(this, SIGNAL(refreshSignal()), position, SLOT(refresh()));

    QHBoxLayout *volumeLayout = new QHBoxLayout(ui->frame_6);
    volumeLayout->setSpacing(0);
    volumeLayout->setContentsMargins(0, 0, 0, 0);
    volume = new MySlider(tr("volumn"), ui->frame_6);
    volume->setOrientation(Qt::Horizontal);
    volume->setRange(0, 999);
    volumeLayout->addWidget(volume);
    connect(this, SIGNAL(refreshSignal()), volume, SLOT(refresh()));

    QGridLayout *lyricLayout = new QGridLayout(ui->frame_9);
    lyricLayout->setSpacing(0);
    lyricLayout->setContentsMargins(0, 0, 0, 0);
    lyric = new Lyric(ui->frame_9);
    lyricLayout->addWidget(lyric);
    connect(this, SIGNAL(refreshSignal()), lyric, SLOT(refresh()));

    QGridLayout *coverLayout = new QGridLayout(ui->frame_4);
    coverLayout->setSpacing(0);
    coverLayout->setContentsMargins(0, 0, 0, 0);
    cover = new AlbumCover(ui->frame_4);
    coverLayout->addWidget(cover);
    connect(this, SIGNAL(refreshSignal()), cover, SLOT(refresh()));

    listButtonLayout = new QVBoxLayout(ui->frame_13);
    listButtonLayout->setSpacing(0);
    listButtonLayout->setContentsMargins(0, 0, 0, 0);

    //this->setWindowOpacity(0.9);

    read_key_value();

}

MainWindow::~MainWindow()
{
    if( ! playlists.isEmpty() )
    {
        QList<Playlist *>::iterator i;
        for(i = playlists.begin(); i < playlists.end(); i++)
            delete *i;
        playlists.clear();
    }
    delete ui;
}

void MainWindow::refresh()
{
    ui->tableView->clearSelection();

    if( ! playlists.isEmpty() )
    {
        QList<Playlist *>::iterator i;
        for(i = playlists.begin(); i < playlists.end(); i++)
            delete *i;
        playlists.clear();
    }

    QLayoutItem *child;
    while ((child = listButtonLayout->takeAt(0)) != 0)
        delete child;

    listButtons.clear();

    if( 0 == (total_list = (unsigned int)LIST_end_list()) )
        return;

    for( unsigned int i=0 ; i < total_list ; i++ )
    {
        listButtons.append( new ListButton( ui->frame_13, i, QString::fromUtf8(LIST_list_name(i))) );
        QObject::connect( listButtons[i], SIGNAL(list_clicked(unsigned int)), this, SLOT(change_list(unsigned int)) );
        QObject::connect( listButtons[i], SIGNAL(list_delete(unsigned int)), this, SLOT(delete_list(unsigned int)) );
        listButtonLayout->addWidget(listButtons[i]);

        playlists.append( new Playlist(i) );
        QObject::connect( ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(playback(QModelIndex)));
    }

    listButtons.first()->setIsHead(true);
    listButtons.last()->setIsTail(true);

    if(cur_list < total_list ){
        change_list( cur_list );
        listButtons.at( cur_list )->setChecked(true);
    }else{
        change_list( total_list - 1);
        listButtons.last()->setChecked(true);
    }
}

void MainWindow::timer_timeout()
{
    if( timer_of_timer == 0 ){
        while( !STATUS_flags( QString("COMPLETED").toUtf8().data() ) );
        refresh();
    }

    if( STATUS_flags( QString("PLAYING").toUtf8().data()) ){
        ui->play->setIcon( QIcon(":/icon/pause.png") );
    }else{
        ui->play->setIcon( QIcon(":/icon/play.png") );
    }

    if( STATUS_flags( QString("STOPPED").toUtf8().data()) ){
        setWindowTitle( tr("SandCat") );
    }else{
        if(STATUS_now_playing() != NULL)
            setWindowTitle( tr(STATUS_now_playing()->artist) + tr(" - ") + tr(STATUS_now_playing()->title) );
    }

    if( timer_of_timer & 4 ){
        ui->mute->setChecked ( STATUS_mute_on() );
        if( STATUS_now_playing() != NULL ){
            long duration_msec = ENTRY_duration( STATUS_now_playing() ) / 1000;
            QTime durationTime(0,0,0,0);
            durationTime = durationTime.addMSecs(duration_msec);
            long cur_msec = ( (double)duration_msec / 1000 * STATUS_position() );
            QTime curTime(0,0,0,0);
            curTime = curTime.addMSecs(cur_msec);
            ui->time->setText( curTime.toString(tr("mm:ss")) + tr("/") + durationTime.toString(tr("mm:ss")) );
        }
        emit refreshSignal();
    }



    if( STATUS_flags( QString("ADDING").toUtf8().data() ) ){
        //do something;
        ui->tableView->setEnabled(false);

        if( STATUS_flags( QString("COMPLETED").toUtf8().data() ) ){
            refresh();
            list_clear_status();
            ui->tableView->setEnabled(true);
            usleep(1);
        }else{
            //do something;
        }
    }

    if( STATUS_flags( QString("DELING").toUtf8().data() ) ){
        //do something;
        ui->tableView->setEnabled(false);

        if( STATUS_flags( QString("COMPLETED").toUtf8().data() ) ){
            refresh();
            list_clear_status();
            ui->tableView->setEnabled(true);
            usleep(1);
        }else{
            //do something
        }
    }

    timer_of_timer++;

    update();
}

void MainWindow::read_key_value()
{
    char *value;
    main_config_get( "[ui]cur_list", &value );
    if( QString(value) == QString("_NOTHING_") ) value = QString("0").toUtf8().data();
    sscanf( value, "%d", &cur_list );
}

void MainWindow::shut_down()
{
    main_shutdown();
}

void MainWindow::change_list( unsigned int listNum )
{
    if( cur_list < static_cast<unsigned int>( listButtons.size()-1 ) )
        listButtons.at(cur_list + 1)->setIsAfterChecked(false);
    if( listNum < static_cast<unsigned int>( listButtons.size()-1 ) )
        listButtons.at(listNum + 1)->setIsAfterChecked(true);


    ui->tableView->setModel(playlists.at(listNum));
    ui->tableView->setColumnHidden(0, true);
    ui->tableView->setColumnHidden(1, true);
    QHeaderView * hvh = ui->tableView->horizontalHeader();
    hvh->setResizeMode(2, QHeaderView::ResizeToContents);
    hvh->setResizeMode(3, QHeaderView::Stretch);
    hvh->resizeSection(4, ui->tableView->width() / 4);
    ui->tableView->resizeRowsToContents();

    cur_list = listNum;
    char *value = new char[50];
    sprintf( value, "%d", cur_list);
    main_config_set( "[ui]cur_list", value );

}

void MainWindow::delete_list( unsigned int listNum )
{
    list_del( listNum );
}

//--------------------------------------------------------------------
void MainWindow::playback(QModelIndex index)
{
    cur_entry = index.row();
    QModelIndex entryOffsetIndex = index.model()->index(cur_entry, 2);
    int entryOffset = playlists.at(cur_list)->data(entryOffsetIndex).toString().toInt();

    audio_playback(false, cur_list, entryOffset);
}

void MainWindow::on_prev_released()
{   
    audio_playback( true, 0, -1 );
}

void MainWindow::on_next_released()
{
    audio_playback( true, 0, +1 );
}

void MainWindow::on_play_released()
{
    if( STATUS_flags( QString("PLAYING").toUtf8().data() ) ){
        audio_pause();
        ui->play->setIcon( QIcon(":/icon/play.png") );
    }else{
        audio_playback( true, 0, 0 );
        ui->play->setIcon( QIcon(":/icon/pause.png") );
    }
}

void MainWindow::on_stop_released()
{
    audio_stop();
}

void MainWindow::on_mute_clicked(bool checked)
{
    audio_volume( true, 0, checked );
}

void MainWindow::on_addList_released()
{
    QDir path( QFileDialog::getExistingDirectory(this, tr("Search Music"),
                                                 "~",
                                                 QFileDialog::ShowDirsOnly
                                                 | QFileDialog::DontResolveSymlinks) );
    list_add( path.absolutePath().toUtf8().data(), path.dirName().toUtf8().data() );
}
